package net.xinqushi.gc;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;

/**
 * 四种引用，四种不同回收策略
 */
public class ReferenceDemo {

    String name;
    ReferenceDemo() {

    }
    public ReferenceDemo(String name) {
        this.name = name;
    }

    static Thread main;
    public static void main(String[] args) {
        main = Thread.currentThread();
        //WeakReference
        WeakReference<ReferenceDemo> weakReference = new WeakReference<ReferenceDemo>(new ReferenceDemo("WeakReference")){
            @Override
            protected void finalize() throws Throwable {
                super.finalize();
                System.out.println("xxx has been finalized ");
            }
        };
        HashMap<Integer,Object> map = new HashMap<>();
        map.put(1,weakReference);
        System.gc();
        //SoftReference
        SoftReference<ReferenceDemo> softReference = new SoftReference<>(new ReferenceDemo("SoftReference"));
        map.put(2,softReference);
        System.gc();
        //假象引用
        ReferenceQueue queue = new ReferenceQueue();
        PhantomReference ref = new PhantomReference(new ReferenceDemo("PhantomReference"), queue);
        System.out.println(ref.get());
        map.put(3,new ReferenceDemo());
        System.gc();
        //StrongReference
        map.put(4,new ReferenceDemo("StrongReference"));
        System.gc();
//        new Thread(()->{
//            while (true) {
//                System.gc();
//                try {
//                    if (null != main && main.isAlive())
//                        Thread.sleep(3 * 1000L);//1s
//                    else
//                        break;
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
   }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println(name +  "  has been finalized ");
    }
}
